package edu.arizona.arid.akshen.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import edu.arizona.arid.akshen.ProgressReportDelegate;

public class Http {
	
	public static String get(String url) throws IOException {
		return get(url, null);
	}
	
	public static String get(String url, ProgressReportDelegate delegate) throws IOException {
		HttpConnection hcon = null;
		DataInputStream dis = null;
		StringBuffer strbuf = new StringBuffer();

		hcon = (HttpConnection) Connector.open(url);
		dis = new DataInputStream(hcon.openInputStream());
		//hcon.getLength();
		
		int read = 0;
		byte[] buf = new byte[4096];
		while ((read = dis.read(buf)) != -1) {
			strbuf = strbuf.append(new String(buf, 0, read));
		}

		dis.close();
		hcon.close();

		return new String(strbuf);
	}
	
	public static String post(final String url, Hashtable data) throws IOException {
		return post(url, data, null);
	}

	public static String post(final String url, Hashtable data, ProgressReportDelegate delegate) throws IOException {
		final StringBuffer requestBody = new StringBuffer();
		// requestBody.append("\r\n\r\n");

		Enumeration keys = data.keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			requestBody.append(key);
			requestBody.append("=");
			requestBody.append(data.get(key));
			requestBody.append("&");
		}
		requestBody.deleteCharAt(requestBody.length()-1);

		StringBuffer strbuf = new StringBuffer();
		try {
			HttpConnection connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
			connection.setRequestMethod(HttpConnection.POST);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			DataOutputStream out = new DataOutputStream(connection
					.openDataOutputStream());
			out.write(new String(requestBody).getBytes());
			out.flush();
			out.close();
			
			System.out.println(new String(requestBody));

			DataInputStream in = new DataInputStream(connection.openInputStream());

			int read = 0;
			byte[] buf = new byte[4096];
			while ((read = in.read(buf)) != -1) {
				strbuf = strbuf.append(new String(buf, 0, read));
			}

			in.close();
			connection.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}

		
		return new String(strbuf);
	}
}
